<?php

namespace App\Listeners;

use App\Constant\QueueKey;
use App\Events\R360GetCertPicEvent;
use App\Facades\Rong360RequestFacade;
use App\Facades\SamLogFacade;
use App\Models\UserCertOcr;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Storage;

class R360GetCertPicEventListener implements ShouldQueue
{
    use InteractsWithQueue;

    public $queue = QueueKey::QUEUE_R360_DOWN_CERT_PIC;

    public $path = 'frontend/cert_file';

    public $relation = [
        'ID_Positive'=>'id_card_front',
        'ID_Negative'=>'id_card_back',
        'photo_assay'=>'hand_cert',
    ];
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  R360GetCertPicEvent  $event
     * @return void
     */
    public function handle(R360GetCertPicEvent $event)
    {
        $user_id = $event->user_id;
        $tokens = $event->tokens;
        $order_no = $event->order_no;
        $ocr = UserCertOcr::where(['user_id'=>$user_id,'is_valid'=>'1'])->first();
        foreach ($tokens as $key => $token){
            $image_data = Rong360RequestFacade::imageInfo($order_no,$token);
            $save_file_name = $this->path.md5(time() . 'file' . 'kskd').'.jpg';
            try{
                Storage::disk('oss')->put($save_file_name,$image_data);
            }catch(\Exception $e){
                SamLogFacade::debug("r360用户{$user_id}上传{$key}图片失败:{$e->getMessage()}");
                continue;
            }
            $url = Storage::disk('oss')->url($save_file_name);
            $ocr->$this->relation[$key] = $url;
        }
        $ocr->save();
    }
}
